local component = require("component")
local event = require("event")
local srlz = require("serialization")
local modem = component.modem

local cdtplib = {}
cdtplib["port"] = 7779
cdtplib["remote"] = nil

function cdtplib.registerUser(balance)
  print("test")
  local balance = balance or 500
  local statusCode, result = sendData("register", {balance})

  if statusCode == 200 then
    return result[1]
  else
    return false
  end
end

function cdtplib.getBalance(id)
  local statusCode, result = sendData("get_balance", {id})

  if statusCode == 200 then
    return result[1]
  else
    return false
  end
end

function cdtplib.setBalance(id, balance)
  local statusCode, result = sendData("set_balance", {id,balance})

  if statusCode == 200 then
    return result
  else
    return false
  end
end

function sendData(op, dataTable, remote)
  modem.open(cdtplib["port"])
  local data = srlz.serialize(dataTable)
  if not cdtplib["remote"] then
    modem.broadcast(cdtplib["port"], op, data)
  else
    modem.send(cdtplib["remote"], cdtplib["port"], op, data)
  end

  local remote, statusCode, srlzdRes

  if not cdtplib["remote"] then
      _, _, remote, _, _, statusCode, srlzdRes = event.pull(3,"modem_message")
	  if srlzdRes then res = srlz.unserialize(srlzdRes) end
  end
  if not res then
	  status = 404
	  res = {}
  end

  return statusCode, res
end

return cdtplib
